package org.pvt.gui;

import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.pvt.R;

/**
 * @author Pavel Talanov
 */
public abstract class BasicCRUDActivity extends ListActivityWithMainMenu {

    @Nullable
    private /*var*/ Cursor cursor;

    @NotNull
    protected abstract Cursor getNewCursor();

    @NotNull
    protected abstract CursorAdapter getCursorAdapter(@NotNull Cursor cursor);

    protected abstract void addItem(@NotNull String text);

    protected abstract void updateItem(long id, @NotNull String newText);

    protected abstract void deleteItem(long id);

    protected final void resetCursorAdapter() {
        stopManagingCursor(cursor);
        if (cursor != null) {
            cursor.close();
        }
        cursor = getNewCursor();
        startManagingCursor(cursor);
        setListAdapter(getCursorAdapter(cursor));
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void onAddClick(@NotNull View view) {
        EditText edit = (EditText) findViewById(R.id.addEventEdit);
        String text = edit.getText().toString();
        if (!validateText(text)) {
            return;
        }
        addItem(text);
        edit.setText("");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (cursor == null) {
            return;
        }
        stopManagingCursor(cursor);
        cursor.close();
    }

    public final boolean validateText(@NotNull String text) {
        boolean cond = text.length() >= 3;
        if (!cond) {
            Toast.makeText(this, R.string.textTooShortMessage, Toast.LENGTH_SHORT).show();
        }
        return cond;
    }
}
